package com.lcredu.seckill.controller;

import com.lcredu.seckill.pojo.SeckillGoods;
import com.lcredu.seckill.pojo.User;
import com.lcredu.seckill.service.GoodsService;
import com.lcredu.seckill.service.SeckillGoodsService;
import com.lcredu.seckill.service.UserService;
import com.lcredu.seckill.util.MD5Util;
import com.lcredu.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 黎长容
 * @date 2025-08-24 18:58
 */
@Slf4j
@Controller
@RequestMapping("/goods")
//@SuppressWarnings("all")
public class GoodsController  {
    @Resource
    private UserService userService;

    @Resource
    private SeckillGoodsService seckillGoodsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 用户登录成功后跳转到List主页
     *
     * @param model 传递数据的model
     *              //     * @param userTicker 用户票据
     * @return 跳转页面
     */
    //去DB获取
//    @RequestMapping("/toList")
////    public String toList(HttpSession session, Model model, @CookieValue("userTicket") String userTicker) {
////    public String toList(HttpServletRequest request, HttpServletResponse response, Model model, @CookieValue("userTicket") String userTicker) {
//    public String toList(Model model, User user) {
//        //1.判断用户是否登录(cookie,session)
////        if (!StringUtils.hasText(userTicker)) {
////            return "login";
////        }
//
////        User user = (User) session.getAttribute(userTicker);
//        //修改为从redis中查询
////        User user = userService.getUser(userTicker, request, response);
////        log.info("user={}", "user:" + userTicker);
////        log.info("user={}", user);
////
////        if (user == null) {
////            return "login";
////        }
//
//        if (user == null) {
//            return "login";
//        }
//
//
//        //2.加入model进行传输
//        model.addAttribute("user", user);
//        model.addAttribute("goodsList", seckillGoodsService.listGoodsVos());
//        return "goodsList";
//    }


//    //去redis中获取(V2.0)
//    //1.先从redis中进行获取
//    //2.如果获取到了就直接返回页面,但是要以JSON格式进行返回了
//    //3.如果没有获取到,手动渲染并存储到redis中
//    @SuppressWarnings("all")
//    /**
//     * 处理toList请求，返回HTML格式的响应内容
//     *
//     * @param value    请求映射路径为"/toList"
//     * @param produces 指定响应内容类型为"text/html;charset=utf-8"
//     * @return 返回HTML格式的页面内容，字符编码为UTF-8
//     */
//    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
//    @ResponseBody
//    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
//
//        if (user == null) {
//            return "login";
//        }
//
//        // 获取Redis模板中的值操作对象，用于执行Redis的键值对操作
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//
//        String html = (String) valueOperations.get("goodList");
//        if (StringUtils.hasText(html)) {
//            return html;
//        }
//
//
//        //2.加入model进行传输
//        model.addAttribute("user", user);
//        model.addAttribute("goodsList", seckillGoodsService.listGoodsVos());
//
//
//        //如果redis中并没有找到就在这里进行传入
//        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
//        // 使用Thymeleaf模板引擎处理"goodsList"模板，生成HTML内容
//        // 参数: "goodsList" - 模板名称，webContext - Web上下文对象
//        // 返回值: 处理后的HTML字符串
//        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
//        // 检查生成的HTML内容是否非空
//        if (StringUtils.hasText(html)) {
//
//            valueOperations.set("goodList", html, 30, TimeUnit.SECONDS);
//        }
//        return html;
//    }

    //去redis中获取(V2.0)
    //1.先从redis中进行获取
    //2.如果获取到了就直接返回页面,但是要以JSON格式进行返回了
    //3.如果没有获取到,手动渲染并存储到redis中
    @SuppressWarnings("all")
    /**
     * 处理toList请求，返回HTML格式的响应内容
     *
     * @param value    请求映射路径为"/toList"
     * @param produces 指定响应内容类型为"text/html;charset=utf-8"
     * @return 返回HTML格式的页面内容，字符编码为UTF-8
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {

        if (user == null) {
            return "login";
        }

        // 获取Redis模板中的值操作对象，用于执行Redis的键值对操作
        ValueOperations valueOperations = redisTemplate.opsForValue();

        String html = (String) valueOperations.get("goodList");
        if (StringUtils.hasText(html)) {
            return html;
        }


        //2.加入model进行传输
        model.addAttribute("user", user);
        model.addAttribute("goodsList", seckillGoodsService.listGoodsVos());


        //如果redis中并没有找到就在这里进行传入
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        // 使用Thymeleaf模板引擎处理"goodsList"模板，生成HTML内容
        // 参数: "goodsList" - 模板名称，webContext - Web上下文对象
        // 返回值: 处理后的HTML字符串
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        // 检查生成的HTML内容是否非空
        if (StringUtils.hasText(html)) {

            valueOperations.set("goodList", html, 30, TimeUnit.SECONDS);
        }
        return html;
    }

    //根据id到相对应的详情页
//    @GetMapping("/toDetail/{goodsId}")
//    public String toGoodsDetail(Model model, User user, @PathVariable Long goodsId) {
//        //判断user是否为空
//        if (null == user) {
//            return "login";
//        }
//        GoodsVo goodsVo = seckillGoodsService.getGoodsVoById(goodsId);
//
//        //设计秒杀
//        //秒杀状态变量
//        //1 secKillStatus  0: 秒杀未开始 1:秒杀进行中 2:秒杀已结束
//        //2 remainSeconds  剩余秒数>0 : 表示还有多久开始秒杀
//        //                 剩余秒数=0 : 表示秒杀已经开始
//        //                 剩余秒数-1 : 表示秒杀已经结束
//
//        LocalDateTime startDate = goodsVo.getStartDate();
//        LocalDateTime endDate = goodsVo.getEndDate();
//        LocalDateTime nowData = LocalDateTime.now();
//
//        int secKillStatus = 0;
//        int remainSeconds = 0;
//
//        if (nowData.isBefore(startDate)) {
//            //秒杀未开始
//            secKillStatus = 0;
//            remainSeconds = (int) Duration.between(nowData, startDate).getSeconds();
//        } else if (nowData.isAfter(endDate)) {
//            //秒杀已结束
//            secKillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            //秒杀进行中
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//
//        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        String endDateStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//        model.addAttribute("secKillStatus", secKillStatus);
//        model.addAttribute("remainSeconds", remainSeconds);
//
//        model.addAttribute("user", user);
//        model.addAttribute("goods", goodsVo);
//        model.addAttribute("startDateStr", startDateStr);
//        model.addAttribute("endDateStr", endDateStr);
//        return "goodsDetail";
//    }


    @GetMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf8")
    @ResponseBody
    public String toGoodsDetail(Model model, User user, @PathVariable Long goodsId,
                                HttpServletRequest request, HttpServletResponse response) {
        //判断user是否为空
        if (null == user) {
            return "login";
        }

        // 获取Redis模板中的值操作对象，用于执行Redis的键值对操作
        ValueOperations valueOperations = redisTemplate.opsForValue();

        String html = (String) valueOperations.get("goodDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        GoodsVo goodsVo = seckillGoodsService.getGoodsVoById(goodsId);

        //设计秒杀
        //秒杀状态变量
        //1 secKillStatus  0: 秒杀未开始 1:秒杀进行中 2:秒杀已结束
        //2 remainSeconds  剩余秒数>0 : 表示还有多久开始秒杀
        //                 剩余秒数=0 : 表示秒杀已经开始
        //                 剩余秒数-1 : 表示秒杀已经结束

        LocalDateTime startDate = goodsVo.getStartDate();
        LocalDateTime endDate = goodsVo.getEndDate();
        LocalDateTime nowData = LocalDateTime.now();

        int secKillStatus = 0;
        int remainSeconds = 0;

        if (nowData.isBefore(startDate)) {
            //秒杀未开始
            secKillStatus = 0;
            remainSeconds = (int) Duration.between(nowData, startDate).getSeconds();
        } else if (nowData.isAfter(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        String startDateStr = startDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endDateStr = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        model.addAttribute("user", user);
        model.addAttribute("goods", goodsVo);
        model.addAttribute("startDateStr", startDateStr);
        model.addAttribute("endDateStr", endDateStr);
        //如果redis中并没有找到就在这里进行传入
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        // 使用Thymeleaf模板引擎处理"goodsList"模板，生成HTML内容
        // 参数: "goodsList" - 模板名称，webContext - Web上下文对象
        // 返回值: 处理后的HTML字符串
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        // 检查生成的HTML内容是否非空
        if (StringUtils.hasText(html)) {

            valueOperations.set("goodsDetail:" + goodsId, html, 30, TimeUnit.SECONDS);
        }
        return html;
    }
    
}
